import axios, { type AxiosResponse } from "axios";
import cookie from "js-cookie";
import qs from "qs";
import router from "@/router";
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import { useUserStore } from "@/stores/admin";

declare interface TypeResponse extends AxiosResponse {
  errno: number,
  errmsg: string
}


let baseURL = "";
if (process.env.NODE_ENV === "development") {
  baseURL = "/api";
} else {
  baseURL = "http://zxwyit.cn:8989/m.api";
}

//创建axios实列
const instance = axios.create({
  baseURL,
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  timeout: 5000
});
//添加请求拦截器
instance.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  if (config.headers) {
    NProgress.start()
    config.headers["AdminToken"] = cookie.get("token") + "";
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  console.error("请求错误", error)
  return Promise.reject(error);
});


// //添加响应拦截器
// instance.interceptors.response.use( res=> {
//     NProgress.done()
//     // 对响应数据做点什么
// 	  let data = res.data
//     let {error,errmsg} = data
//     let path = router.currentRoute.value.fullPath
//     if(10006===error){
//       ElMessage.error(errmsg)
//       router.replace({path:"/login",query:{back:path}})
//       return
//     }
// 		return data;

//   }, function (error) {
//     // 对响应错误做点什么
//     console.error("请求响应错误",error)
//     return Promise.reject(error);
//   });
// 响应拦截器
// 定义需要无感刷新令牌的请求类型
const Refresh = ["edit", "create", "delete"]
instance.interceptors.response.use(
  async function (response) {
    let data = response.data
    let path = router.currentRoute.value.fullPath
    if (10006 === data.errno) {
      const configData = response.config.data || ""
      console.log(response)
      var index = Refresh.findIndex(item => configData.includes(item))
      // 需要重新登录
      if (-1 == index) {
        ElMessage.error(data.errmsg)
        router.replace({ path: "/login", query: { back: path } })
        return
        // 刷新令牌
      } else {
        const store = useUserStore();
        const { username, password } = store.user
        const loginData = { _gp: "admin", _mt: "login", username, password }
        const { errno, errmsg, data } = await post(loginData)
        if (200 == errno) {
          cookie.set("token", data) //重新存储令牌
        } else {
          ElMessage.error(errmsg)
          return
        }
        const headersData = response.config.headers || {}
        headersData.AdminToken = data
        let res = await axios.request(response.config)
        if (200 == res.data.errno) {
          return res.data
        } else {
          ElMessage.error(res.data.errmsg)
          return
        }
      }
    }
    NProgress.done()
    return data
  },
  function (error) {
    console.error("请求响应错误", error)
    return Promise.reject(error)
  }
)


function get(params?: object): Promise<TypeResponse> {
  return instance.get("", { params });
}
function post(data: object, params?: object): Promise<TypeResponse> {
  return instance.post("", qs.stringify(data), { params })
}
// 富文本图片请求
export function upload(data: object): Promise<TypeResponse> {
  return instance.post("../upload/admin", data);
}
export {
  get,
  post
}